package com.lagou.sessionshare.Interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author: jie.zhao
 * @create: 2021/03/29 11:08
 */
@Configuration
public class LoginHandlerInterceptor implements HandlerInterceptor {



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getRequestURI().contains("login") || request.getRequestURI().contains("error")){
            return true;
        }

        HttpSession session = request.getSession();
        Object username = session.getAttribute("username");
        if (username != null) {
            return true;
        } else {
            request.setAttribute("login_error", "请先登录");
//            request.getRequestDispatcher("/").forward(request, response);
            response.getWriter().write("no login");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
